import React, { Component } from 'react';
import {high,base,ajax,getMultiLang} from 'nc-lightapp-front';
const { NCFormControl: FormControl, NCDatePicker: DatePicker, NCButton: Button, NCRadio: Radio, NCBreadcrumb: Breadcrumb,
    NCRow: Row, NCCol: Col, NCTree: Tree, NCIcon: Icon, NCLoading: Loading, NCTable: Table, NCSelect: Select,
    NCCheckbox: Checkbox, NCNumber, AutoComplete, NCDropdown: Dropdown, NCPanel: Panel,NCModal:Modal,NCForm
} = base;
  const defaultProps12 = {
    prefixCls: "bee-table",
    multiSelect: {
      type: "checkbox",
      param: "key"
    }
  };

import drawinAssidData from '../drawingAssidData/index.js';
import './index.less'
export default class AssidModal extends Component {
    constructor(props) {
        super(props);

        this.state = {
            json:{},
            showModal:false,
            isShowUnit:false,//是否显示业务单元
            assData: [//辅助核算信息
            ],
            childAssData:[],//接受父组件传过来的参数
            loadData:[],//查询模板加载数据
            listItem:{},//模板数据对应值
            checkedAll:true,//默认全选中
            SelectedAssData:[],//选中的数据
            checkedArray: [
            ],
        };
        this.close = this.close.bind(this);
    }

    updateOriginData(originData, v, multiSelect){
        let refnameArr=[],refpkArr=[],refcodeArr=[];
        if (originData) {
            if(multiSelect){
                v.map((arr,index)=>{
                        refnameArr.push(arr.refname);
                        refpkArr.push(arr.refpk);
                        refcodeArr.push(arr.refcode);
                
                })
            }else{
                refnameArr.push(v.refname);
                refpkArr.push(v.refpk);
                refcodeArr.push(v.refcode);
            }    
            originData.checkvaluename = refnameArr;
            originData.pk_Checkvalue = refpkArr;
            originData.checkvaluecode=refcodeArr;
        }
    }
    updateOriginDataNonDoc(originData, v){
        if (originData) {
            let assArr=[];
            assArr.push(v);
            originData.checkvaluename = assArr;
            originData.pk_Checkvalue =assArr;
            originData.checkvaluecode=assArr;
        }
    }

    //字符转换为数组
    strChangetoArr(str){
        if(str.indexOf(',')!=-1){
            return str.split(',');
        }else{
            return [str]
        }
    }
    componentDidMount(){
        if(this.props.componentRef)
            this.props.componentRef(this);
    }

    componentWillUnmount(){
    }
    
    componentWillUpdate(nextProps, nextState){
        /** 
            *父组件传递过来的pretentAssData里包含 
            *   pk_accountingbook,
            *    pk_accasoa,
            *    prepareddate,
            *    pk_org,
            *   assData,
            *   assid, 
            *   checkboxShow,是否显示复选框 true、false
            *   checkedAll 是否全选中 true， false
            *   pk_defdoclist,
            */ 
           if(this.props.pretentAssData.pk_accasoa === nextProps.pretentAssData.pk_accasoa){
                return false
           }
            let self=this;
            let {checkedAll,assData,checkedArray,childAssData}=self.state;
            let {pretentAssData}=nextProps;
            checkedArray=[];
        if(childAssData!=pretentAssData){              
            childAssData=pretentAssData;
            if(pretentAssData.checkedAll){//接收父组件传递过来的checkedAll
                checkedAll=pretentAssData.checkedAll;
            }else{
                checkedAll=true;
            }
            if(pretentAssData.assData && pretentAssData.assData.length>0){
                pretentAssData.assData.map((item,index)=>{
                    item.key=index;
                    checkedArray.push(true);//默认选中
                })
                self.setState({
                    assData:pretentAssData.assData,
                    childAssData,checkedArray
                })
            }else if(pretentAssData.assid&&pretentAssData.assid!=""){
                let assidParam={
                    pk_accasoa:pretentAssData.pk_accasoa,
                    date:pretentAssData.prepareddate,
                    assid:pretentAssData.assid
                }
                ajax({
                    url:'/nccloud/gl/voucher/queryAssTypeAndValue.do',
                    data:assidParam,
                    success: function(response){
                        const { data,success } = response;
                        if(data){
                            if(data.length>0){
                                data.map((item,index)=>{
                                    item.key=index;
                                    checkedArray.push(checkedAll);
                                    item.m_classid=item.classid;
                                    item.pk_Checktype=item.pk_accassitem;
                                    if(item.checkvaluecode){
                                        item.checkvaluecode=self.strChangetoArr(item.checkvaluecode);
                                    }
                                    if(item.checkvaluename){
                                        item.checkvaluename=self.strChangetoArr(item.checkvaluename);
                                    }
                                    if(item.pk_Checkvalue){
                                        item.pk_Checkvalue=self.strChangetoArr(item.pk_Checkvalue);
                                    }
                                })
                            }
                        }
                        childAssData.assData=data;
                        self.setState({
                            assData:data,
                            childAssData
                        })
                    }
                })
            }else{
                assData=[];
                //请求辅助核算数据
                let url = '/nccloud/gl/voucher/queryAssItem.do';
                if(pretentAssData.pk_accasoa&&pretentAssData.pk_accasoa!=""&&pretentAssData.prepareddate&&pretentAssData.prepareddate!=""){
                    let queryData = {
                        pk_accasoa:pretentAssData.pk_accasoa,
                        prepareddate: pretentAssData.prepareddate,
                    };
                
                    /* 是否包含下级科目辅助核算，默认不包含 */
                    if(nextProps.hasOwnProperty('includeSubAss') && nextProps.includeSubAss){
                        queryData.includeSub = nextProps.includeSubAss;
                    }
                
                    ajax({
                        url:url,
                        data:queryData,
                        success: function(response){
                            const { success } = response;
                            //渲染已有账表数据遮罩
                            if(pretentAssData.checkedArray){
                                pretentAssData.checkedArray.length = 0;
                                // pretentAssData.checkedArray.push(checkedAll);
                            }
                            if (success) {
                                if(response.data){
                                    if(response.data.length>0){
                                        response.data.map((item,index)=>{
                                            item.key=index;
                                            checkedArray.push(checkedAll);//默认选中
                                            if(pretentAssData.checkedArray){
                                                pretentAssData.checkedArray.push(checkedAll);
                                            }
                                            let obj={
                                                key:index,
                                                "checktypecode":item.code,
                                                "checktypename" :item.name,
                                                "pk_Checktype": item.pk_accassitem,
                                                "refCode":item.refCode?item.refCode:item.code,
                                                "refnodename":item.refnodename,
                                                "pk_accassitem":item.pk_accassitem,
                                                "m_classid":item.classid,
                                                "pk_accountingbook": pretentAssData.pk_accountingbook,
                                                "classid": item.classid,
                                                "pk_defdoclist": item.classid,
                                                // "inputlength": item.inputlength || '',
                                                // "digits": item.digits || ''
                                            }
                                            assData.push(obj);
                                        })
                                        
                                    }
                                }
                                childAssData.assData=assData;
                                self.setState({
                                    assData,childAssData,checkedArray
                                })
                            }   
                        }
                    });
                }else{
                    /* 科目主键或者业务日期为空时清空辅助核算信息 */
                    self.setState({
                        assData,
                        childAssData:assData,
                        checkedArray:[]
                    });
                }
            }
        }
    }
    

    //表格操作根据key寻找所对应行
	findByKey(key, rows) {
		let rt = null;
		let self = this;
		rows.forEach(function(v, i, a) {
			if (v.key == key) {
				rt = v;
			}
		});
		return rt;
	}

    close() {
        this.props.handleClose();
    }
    //确定 过滤勾选的数据
    exportAssData=()=>{
        let self=this;
        let { SelectedAssData,checkedArray,listItem,assData,childAssData } =self.state;
        SelectedAssData=[];//清空
        for(var i = 0; i < checkedArray.length; i++){
            if(checkedArray[i]==true){
                SelectedAssData.push(assData[i]);
            }
        }
        return SelectedAssData;
    }
    //全选
    onAllCheckChange = () => {
        let self = this;
        let checkedArray = [];
        for (var i = 0; i < self.state.checkedArray.length; i++) {
          checkedArray[i] = !self.state.checkedAll;
        }
        self.setState({
          checkedAll: !self.state.checkedAll,
          checkedArray: checkedArray,
        });
        if(self.props.pretentAssData.checkedArray){
            self.props.pretentAssData.checkedArray.length = 0;
            checkedArray.map((item) => self.props.pretentAssData.checkedArray.push(item));
        }
      };
      //单选
      onCheckboxChange = (text, record, index) => {
        let self = this;
        let allFlag = false;
        let checkedArray = self.state.checkedArray.concat();
        checkedArray[index] = !self.state.checkedArray[index];
        for (var i = 0; i < self.state.checkedArray.length; i++) {
          if (!checkedArray[i]) {
            allFlag = false;
            break;
          } else {
            allFlag = true;
          }
        }
        self.setState({
          checkedAll: allFlag,
          checkedArray: checkedArray,
        });
        if(self.props.pretentAssData.checkedArray){
            self.props.pretentAssData.checkedArray.length = 0;
            checkedArray.map((item) => self.props.pretentAssData.checkedArray.push(item));
        }
      };
      
      isAllSelect(checkedArray){
          let checkedAll = true;
          if(checkedArray&&checkedArray.length>0){
              checkedArray.map((item)=>{
                  checkedAll = checkedAll && item;
              })
          }else{
            checkedAll = false;
          }
          return checkedAll;
      }

      renderColumnsMultiSelect(columns) {
        const {checkedArray } = this.state;
        const { multiSelect } = this.props;
        let select_column = {};
        let indeterminate_bool = false;
        if (multiSelect && multiSelect.type === "checkbox") {
          let i = checkedArray.length;
          while(i--){
              if(checkedArray[i]){
                indeterminate_bool = true;
                break;
              }
          }
          let defaultColumns = [
            {
              title: (
                <Checkbox
                  className="table-checkbox"
                  checked={this.state.checkedAll&&this.isAllSelect(checkedArray)}
                  indeterminate={indeterminate_bool&&!this.isAllSelect(checkedArray)}
                  onChange={this.onAllCheckChange}
                />
              ),
              key: "checkbox",
              attrcode: 'checkbox',
              dataIndex: "checkbox",
              width: "60px",
              render: (text, record, index) => {
                return (
                  <Checkbox
                    className="table-checkbox"
                    checked={this.state.checkedArray[index]}
                    onChange={this.onCheckboxChange.bind(this, text, record, index)}
                  />
                );
              }
            }
          ];
          columns = defaultColumns.concat(columns);
        }
        return columns;
      }
      componentWillMount(){
        let self=this;
        let {childAssData, checkedArray}=self.state;
        if(self.props.pretentAssData.assData && self.props.pretentAssData.assData.length>0){
            childAssData=self.props.pretentAssData;
            checkedArray=self.props.pretentAssData.checkedArray || [];
            self.setState({
                assData:self.props.pretentAssData.assData,
                childAssData,
                checkedArray
            })
        }
		let callback= (json) =>{
            self.setState({
              json:json
				},()=>{
            })
        }
		getMultiLang({moduleId:'publiccomponents',domainName:'gl',currentLocale:'simpchn',callback});
    }
    render() {
        let refMultiSelect = this.props.refMultiSelect;
        let{ showDisableData, pretentAssData, accAssRuleCtrl }=this.props;
        let { loadData,assData, json} =this.state;
        let assDataColumn=[
            {
                title: this.state.json['publiccomponents-000002'],/* 国际化处理： 核算类型名称*/
                dataIndex: "checktypename",
                key: "checktypename",
                width: "30%",
                render: (text, record, index) => {
                  return <span>{record.checktypename}</span>;
                  }
              },
            {
              title: this.state.json['publiccomponents-000003'],/* 国际化处理： 核算内容*/
              dataIndex: "checkvaluename",
              key: "checkvaluename",
              width: "35%",
                render: (text, record, index) => {
                    return (drawinAssidData(this,text, record, index,showDisableData,accAssRuleCtrl))
                }
            }
        ];
        let columnsldad;
        if(pretentAssData.checkboxShow){
            columnsldad = this.renderColumnsMultiSelect(assDataColumn);
        }else{
            columnsldad=assDataColumn;
        }

        
        const emptyFunc = () => <span>{this.state.json['publiccomponents-000007']}！</span>/* 国际化处理： 这里没有数据*/
        return (
            <div className="getAssidData asstable">
                <Table
                    columns={columnsldad} data={assData}
                    emptyText={emptyFunc}
                />
            </div>
        )
    }
}
AssidModal.defaultProps = defaultProps12;
